package com.module.user.service.impl;


import com.common.Constants;
import com.common.PageDto;
import com.exception.BusinessException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.module.user.dao.UsersMapper;
import com.module.user.dao.model.Users;
import com.module.user.pojo.UserPageVo;
import com.module.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@EnableCaching
@CacheConfig(cacheNames = "baseentity")
public class UserServiceImpl implements IUserService {

    @Resource
    private UsersMapper usersMapper;

    @Override
    public Users login(String username, String passwd) {
        Users users = null;
        if(StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(passwd)) {
            users = usersMapper.findByUsernameAndPasswd(username, passwd);
        }else {
            throw new BusinessException("用户与密码不能为空");//业务逻辑返回信息
        }
        return users;
    }

    @Override
    public boolean register(String username, String passwd) {
        Users users = new Users();
        users.setUsername(username);
        users.setPasswd(passwd);
        int cnt = usersMapper.insertSelective(users);
        return cnt > 0;
    }

    @Override
    @Transactional
    public void batchAdd(String username, String passwd) {
        Users users = new Users();
        users.setUsername(username);
        users.setPasswd(passwd);
        usersMapper.insertSelective(users);
        int i = 10 /0;
        users = new Users();
        users.setUsername(username+"2");
        users.setPasswd(passwd);
        usersMapper.insertSelective(users);
    }

    @Override
    public UserPageVo page(String username ,int PageNumber) {
        PageDto pageDto = new PageDto();
        Map<String,Object> map=new HashMap<>();
        map.put("username", username);
        pageDto.setPageNumber(PageNumber);
        pageDto.setPageSize(Constants.DEFAULT_DATA_PAGE_SIZE);
        // 分页查询
        Page<Users> userVoPage = PageHelper.startPage(pageDto).doSelectPage(
                () -> usersMapper.getUserPage(map));
        UserPageVo userPageVo = new UserPageVo();
        userPageVo.setUsersPageInfo(userVoPage.toPageInfo());
        return userPageVo;
    }
}